package com.wang.demo.application.handler;

import com.wang.demo.protocol.message.GroupJoinRequestMessage;
import com.wang.demo.protocol.message.GroupJoinResponseMessage;
import com.wang.demo.service.GroupSession;
import com.wang.demo.service.factory.GroupSessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Set;

/**
 * @author: Jeffrey
 * @date: 2022/01/20/8:31
 * @description:
 */
@ChannelHandler.Sharable
public class GroupJoinRequestMessageHandler extends SimpleChannelInboundHandler<GroupJoinRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupJoinRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        String username = msg.getUsername();

        Set<String> members = GroupSessionFactory.getGroupSession().getMembers(groupName);
        if (members.contains(username)){
            GroupJoinResponseMessage message = new GroupJoinResponseMessage(false,"你已经在群中！");
            ctx.writeAndFlush(message);
        }else{
            GroupSession session = GroupSessionFactory.getGroupSession();
            session.joinMember(groupName,username);
            /*向所有用户发送有新用户加入*/
            GroupJoinResponseMessage message = new GroupJoinResponseMessage(true,username+"加入群聊"+groupName);
            session.getMembersChannel(groupName)
                    .stream()
                    .forEach((e) ->{
                        e.writeAndFlush(message);
                    });
        }
    }
}
